<template>
  <div class="role-management">
    <el-card>
      <div class="section-title">角色管理</div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="角色名称">
            <el-input 
              v-model="filterForm.roleName" 
              placeholder="请输入角色名称" 
              clearable
              style="width: 200px;"
              class="center-input"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="filterForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px;"
              class="center-input"
            >
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              筛选
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-button 
        type="primary" 
        style="margin-bottom: 16px" 
        @click="openAddDialog"
      >
        <el-icon style="margin-right: 4px;"><Plus /></el-icon>
        新增角色
      </el-button>

      <!-- 数据区域 -->
      <div class="data-area">
        <template v-if="loading">
          <el-skeleton :rows="6" animated style="margin: 32px 0" />
        </template>
        <template v-else>
          <el-table
            :row-key="(row, index) => row.id"
            :data="roleList"
            style="width: 100%"
            :loading="loading"
            :max-height="500"
          >
            <el-table-column prop="Index" label="序号" min-width="80" align="center">
              <template #default="scope">
                {{
                  currentPage.page > 1
                    ? currentPage.page * 10 - 10 + scope.$index + 1
                    : scope.$index + 1
                }}
              </template>
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" min-width="200" align="center">
              <template #default="scope">
                <el-input
                  v-if="editingRowId === scope.row.id"
                  v-model="scope.row.roleName"
                  placeholder="请输入角色名称"
                  class="center-input"
                />
                <span v-else>{{ scope.row.roleName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="300" align="center">
              <template #default="scope">
                <el-input
                  v-if="editingRowId === scope.row.id"
                  v-model="scope.row.description"
                  placeholder="请输入描述"
                  class="center-input"
                />
                <span v-else>{{ scope.row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isActive" label="状态" min-width="100" align="center">
              <template #default="scope">
                <template v-if="editingRowId === scope.row.id">
                  <el-switch
                    v-model="scope.row.isActive"
                    @change="isActive({ active: scope.row.isActive, id: scope.row.id })"
                  />
                </template>
                <template v-else>
                  <el-tag v-if="scope.row.isActive === true" type="success">启用</el-tag>
                  <el-tag v-else type="danger">禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="280" align="center">
              <template #default="scope">
                <template v-if="editingRowId !== scope.row.id">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openEdit(scope.row.id)" 
                    link
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="openAssignPermissions(scope.row)"
                    link
                  >
                    <el-icon><Setting /></el-icon>
                    权限
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="openDelete(scope.row.id)" 
                    link
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
                <template v-else>
                  <el-button type="success" size="small" @click="saveEdit(scope.row.id)" link>
                    <el-icon><Check /></el-icon>
                    保存
                  </el-button>
                  <el-button type="warning" size="small" @click="cancelEdit()" link>
                    <el-icon><Close /></el-icon>
                    取消
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <template v-if="loading">
          <el-skeleton :rows="1" animated style="width: 400px; height: 50px;" />
        </template>
        <template v-else>
          <el-pagination
            :background="background"
            layout="sizes, prev, pager, next, jumper"
            :total="totalSize"
            v-model:current-page="currentPage.page"
            v-model:page-size="currentPage.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="false"
            :class="{ 'pagination-disabled': isDialogOpen }"
          />
        </template>
      </div>
    </el-card>

    <!-- 新增角色对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增角色"
      width="500px"
      :close-on-click-modal="false"
      @close="isDialogOpen = false"
    >
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px" class="add-role-form">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" placeholder="请输入描述" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleAddRole" size="large" :loading="addLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="assignPermissionsDialogVisible"
      title="分配权限"
      width="700px"
      :close-on-click-modal="false"
      top="5vh"
      :lock-scroll="false"
    >
      <div class="assign-permissions-content">
        <div class="role-info">
          <h4>角色：{{ currentRole?.roleName }}</h4>
          <p>描述：{{ currentRole?.description }}</p>
        </div>

                  <div class="permissions-section">
            <div class="section-header">
              <h5>选择权限</h5>
              <span class="selected-count">已选择 {{ selectedPermissions.length }} 个权限</span>
            </div>

          <div class="permissions-container">
            <!-- 左侧类别列表 -->
            <div class="category-list">
              <div 
                v-for="(group, groupKey) in groupedPermissions" 
                :key="groupKey"
                class="category-item"
                :class="{ active: selectedCategory === groupKey }"
                @click="selectCategory(groupKey)"
              >
                <div class="category-info">
                  <span class="category-name">{{ getGroupDisplayName(groupKey) }}</span>
                  <span class="category-count">{{ group.length }}</span>
                </div>
              </div>
            </div>
            
            <!-- 右侧权限内容 -->
            <div class="permissions-content">
              <div v-if="selectedCategory" class="category-permissions">
                <div class="category-header">
                  <div class="category-title-row">
                    <h5>{{ getGroupDisplayName(selectedCategory) }}</h5>
                    <div class="category-actions">
                      <el-button type="primary" size="small" @click="selectAllInCategory">全选</el-button>
                      <el-button type="info" size="small" @click="clearAllInCategory">清空</el-button>
                    </div>
                  </div>
                </div>
                
                <el-checkbox-group v-model="selectedPermissions" class="permissions-list">
                  <el-checkbox
                    v-for="permission in groupedPermissions[selectedCategory]"
                    :key="permission.id"
                    :label="permission.id"
                    class="permission-item"
                    :style="{ height: '80px', minHeight: '80px', maxHeight: '80px' }"
                  >
                    <template #default>
                      <div class="permission-info">
                        <span class="permission-name">{{
                          permission.permissionName || permission.name || "未知权限"
                        }}</span>
                        <span class="permission-desc">{{
                          permission.description || permission.desc || "暂无描述"
                        }}</span>
                      </div>
                    </template>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              
              <div v-else class="no-category-selected">
                <el-empty description="请选择左侧权限类别" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignPermissionsDialogVisible = false" size="large">取消</el-button>
          <el-button
            type="primary"
            @click="handleAssignPermissions"
            size="large"
            :loading="assignPermissionsLoading"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除角色"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-confirm">
        <div class="delete-icon">
          <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
        </div>
        <div class="delete-message">
          <h3>确定要删除该角色吗？</h3>
          <p>此操作不可恢复，请谨慎操作。</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false" size="large">取消</el-button>
          <el-button type="danger" @click="handleDeleteRole" size="large" :loading="deleteLoading"
            >删除</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 定义组件名称
defineOptions({
  name: "RoleIndex",
});

import { ref, onMounted, computed } from "vue";
import { usePermission } from '@/composables/usePermission'
import { ElMessage } from "element-plus";
import {
  getRoleList,
  addRole,
  updateRole,
  deleteRole,
  enableRole,
  disableRole,
  rolePageSize,
} from "@/api/role";
import { getPermissionList, getRolePermissions, assignPermissionToRole } from "@/api/permission";
import { handleApiError } from "@/utils/errorHandler";
import { Edit, Delete, Check, Close, Warning, Setting, Search, Refresh, Plus } from "@element-plus/icons-vue";

const currentPage = ref({ page: 1, pageSize: 10 });
const roleList = ref([]);
const addDialogVisible = ref(false);
// 权限管理
const { handlePermissionDenied } = usePermission()

const addFormRef = ref();
const addForm = ref({ roleName: "", description: "" });
const editingRowId = ref(null);
const deletingRowId = ref(null);
let totalSize = ref(0);
const addRules = {
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入描述", trigger: "blur" }],
};
const loading = ref(true);
const addLoading = ref(false);
const deleteDialogVisible = ref(false);
const deleteLoading = ref(false);
const background = ref(true);
const isDialogOpen = ref(false);

// 分配权限相关
const assignPermissionsDialogVisible = ref(false);
const assignPermissionsLoading = ref(false);
const currentRole = ref(null);
const allPermissions = ref([]);
const selectedPermissions = ref([]);
const selectedCategory = ref('');

// 筛选相关
const filterForm = ref({
  roleName: '',
  status: '',
});

// 获取角色列表
async function fetchRoles(showLoading = true) {
  if (showLoading) {
    loading.value = true;
  }
  try {
          // 获取所有角色数据，不传递筛选参数
      const apiParams = {
        page: 1,
        size: 1000 // 获取所有数据，在前端进行筛选
      };
    
    const response = await rolePageSize(apiParams);
    
    if (response && response.data) {
      let allRoles = response.data.items || [];
      
      // 在前端进行筛选
      let filteredRoles = allRoles.filter(role => {
        // 角色名称筛选
        if (filterForm.value.roleName && !role.roleName.toLowerCase().includes(filterForm.value.roleName.toLowerCase())) {
          return false;
        }
        
        // 状态筛选
        if (filterForm.value.status) {
          const roleStatus = role.isActive ? 'active' : 'inactive';
          if (roleStatus !== filterForm.value.status) {
            return false;
          }
        }
        
        return true;
      });
      
      // 分页处理
      const startIndex = (currentPage.value.page - 1) * currentPage.value.pageSize;
      const endIndex = startIndex + currentPage.value.pageSize;
      roleList.value = filteredRoles.slice(startIndex, endIndex);
      totalSize.value = filteredRoles.length;
      

    } else {
      console.error('角色列表数据格式错误:', response);
      roleList.value = [];
      totalSize.value = 0;
    }
  } catch (error) {
    console.error('加载角色列表失败:', error);
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: true });
    } else {
      handleApiError(error, { showMessage: true });
    }
    roleList.value = [];
    totalSize.value = 0;
  } finally {
    if (showLoading) {
      loading.value = false;
    }
  }
}

// 获取所有权限
async function fetchAllPermissions() {
  try {
    // 获取所有权限，不使用分页限制
    const response = await getPermissionList({
      page: 1,
      size: 1000, // 设置一个很大的数字来获取所有权限
      search: ''
    });

    if (response && response.data) {
            if (Array.isArray(response.data)) {
        allPermissions.value = response.data;
      } else if (response.data.items && Array.isArray(response.data.items)) {
        allPermissions.value = response.data.items;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        allPermissions.value = response.data.data;
      } else {
        allPermissions.value = [];
      }
    } else {
      allPermissions.value = [];
    }
  } catch (error) {
    console.error("获取权限列表失败:", error);
    ElMessage.error("获取权限列表失败，请检查权限设置");

    // 使用数据库中的实际权限数据作为默认值
    allPermissions.value = [
      // 用户管理权限
      {
        id: "1",
        permissionName: "用户查看",
        permissionCode: "user.view",
        description: "允许查看用户信息",
      },
      {
        id: "2",
        permissionName: "用户创建",
        permissionCode: "user.create",
        description: "允许创建新用户",
      },
      {
        id: "3",
        permissionName: "用户编辑",
        permissionCode: "user.edit",
        description: "允许编辑用户信息",
      },
      {
        id: "4",
        permissionName: "用户删除",
        permissionCode: "user.delete",
        description: "允许删除用户",
      },
      {
        id: "5",
        permissionName: "用户管理",
        permissionCode: "user.manage",
        description: "允许管理用户角色",
      },
      
      // 文件管理权限
      {
        id: "6",
        permissionName: "文件查看",
        permissionCode: "file.view",
        description: "允许查看文件列表",
      },
      {
        id: "7",
        permissionName: "文件上传",
        permissionCode: "file.upload",
        description: "允许上传文件",
      },
      {
        id: "8",
        permissionName: "文件删除",
        permissionCode: "file.delete",
        description: "允许删除文件",
      },
      
      // 角色管理权限
      {
        id: "9",
        permissionName: "角色查看",
        permissionCode: "role.view",
        description: "允许查看角色信息",
      },
      {
        id: "10",
        permissionName: "角色创建",
        permissionCode: "role.create",
        description: "允许创建新角色",
      },
      {
        id: "11",
        permissionName: "角色编辑",
        permissionCode: "role.edit",
        description: "允许编辑角色信息",
      },
      {
        id: "12",
        permissionName: "角色删除",
        permissionCode: "role.delete",
        description: "允许删除角色",
      },
      {
        id: "13",
        permissionName: "角色管理",
        permissionCode: "role.manage",
        description: "允许管理角色权限",
      },
      
      // 权限管理权限
      {
        id: "14",
        permissionName: "权限查看",
        permissionCode: "permission.view",
        description: "允许查看权限信息",
      },
      {
        id: "15",
        permissionName: "权限创建",
        permissionCode: "permission.create",
        description: "允许创建新权限",
      },
      {
        id: "16",
        permissionName: "权限编辑",
        permissionCode: "permission.edit",
        description: "允许编辑权限信息",
      },
      {
        id: "17",
        permissionName: "权限删除",
        permissionCode: "permission.delete",
        description: "允许删除权限",
      },
      
      // 系统管理权限
      {
        id: "18",
        permissionName: "系统查看",
        permissionCode: "system.view",
        description: "允许查看系统信息",
      },
      {
        id: "19",
        permissionName: "系统创建",
        permissionCode: "system.create",
        description: "允许创建系统配置",
      },
      {
        id: "20",
        permissionName: "系统编辑",
        permissionCode: "system.edit",
        description: "允许编辑系统配置",
      },
      {
        id: "21",
        permissionName: "系统删除",
        permissionCode: "system.delete",
        description: "允许删除系统配置",
      },
      
      // 日志管理权限
      {
        id: "22",
        permissionName: "日志查看",
        permissionCode: "log.view",
        description: "允许查看操作日志",
      },
      
      // 菜单管理权限
      {
        id: "23",
        permissionName: "菜单查看",
        permissionCode: "menu.view",
        description: "允许查看菜单信息",
      },
      {
        id: "24",
        permissionName: "菜单创建",
        permissionCode: "menu.create",
        description: "允许创建新菜单",
      },
      {
        id: "25",
        permissionName: "菜单编辑",
        permissionCode: "menu.edit",
        description: "允许编辑菜单信息",
      },
      {
        id: "26",
        permissionName: "菜单删除",
        permissionCode: "menu.delete",
        description: "允许删除菜单",
      },
      {
        id: "27",
        permissionName: "菜单管理",
        permissionCode: "menu.manage",
        description: "允许管理菜单角色",
      },

      {
        id: "64",
        permissionName: "安全审计",
        permissionCode: "security.audit",
        description: "允许进行安全审计",
      },
      {
        id: "65",
        permissionName: "密码策略",
        permissionCode: "security.password_policy",
        description: "允许管理密码策略",
      },
    ];
  }
}

// 获取角色权限
async function fetchRolePermissions(roleId) {
  try {
    const response = await getRolePermissions(roleId);
    console.log("角色权限响应数据结构:", {
      hasData: !!response.data,
      dataType: typeof response.data,
      isArray: Array.isArray(response.data),
      dataKeys: response.data ? Object.keys(response.data) : [],
    });

    let rolePermissions = [];

    if (response && response.data) {
      if (Array.isArray(response.data)) {
        rolePermissions = response.data;
      } else if (response.data.items && Array.isArray(response.data.items)) {
        rolePermissions = response.data.items;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        rolePermissions = response.data.data;
      }
    }

    // 将角色权限ID转换为字符串数组，用于复选框对比
    selectedPermissions.value = rolePermissions.map((p) => {
      // 处理不同的数据结构
      let permissionId = null;
      if (typeof p === "string") {
        permissionId = p;
      } else if (p.id) {
        permissionId = p.id.toString();
      } else if (p.permissionId) {
        permissionId = p.permissionId.toString();
      } else {
        permissionId = p.toString();
      }
      return permissionId;
    });
  } catch (error) {
    console.error("获取角色权限失败:", error);
    ElMessage.error("获取角色权限失败");
    selectedPermissions.value = [];
  }
}

onMounted(async () => {
  loading.value = true;
  await fetchRoles();
  await fetchAllPermissions();
  loading.value = false;
});

function openAddDialog() {
  addDialogVisible.value = true;
  addForm.value = { roleName: "", description: "" };
}

// 新增角色
async function handleAddRole() {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    addLoading.value = true;
    try {
      let res = await addRole({
        roleName: addForm.value.roleName,
        description: addForm.value.description,
      });
      if (res.code === 200) {
        ElMessage.success("新增角色成功");
      } else if (res.code === 409) {
        ElMessage.error("角色已经存在");
      }

      addDialogVisible.value = false;
      fetchRoles();
    } catch (error) {
      handleApiError(error, { showMessage: true });
    } finally {
      addLoading.value = false;
    }
  });
}

function openEdit(id) {
  editingRowId.value = id;
}

// 保存编辑
async function saveEdit(id) {
  const row = roleList.value.find((r) => r.id === id || r.Id === id);
  if (!row) return;
  try {
    await updateRole(id, {
      roleName: row.roleName || row.name,
      description: row.description || row.desc,
    });
    ElMessage.success("保存成功");
    editingRowId.value = null;
    fetchRoles();
  } catch (error) {
    handleApiError(error, { showMessage: true });
  }
}

//取消编辑按钮
let cancelEdit = () => {
  editingRowId.value = null;
};
//删除数据
let openDelete = async (id) => {
  deleteDialogVisible.value = true;
  isDialogOpen.value = true;
  // 保存要删除的角色ID，但不进入编辑模式
  deletingRowId.value = id;
  editingRowId.value = null; // 确保不进入编辑模式
};

let isActive = async (obj) => {
  if (obj.active) {
    await enableRole(obj.id);
  } else {
    await disableRole(obj.id);
  }

  await getRoleList();
};

// 打开分配权限对话框
async function openAssignPermissions(role) {
  try {
    currentRole.value = role;
    assignPermissionsDialogVisible.value = true;
    assignPermissionsLoading.value = true;

    // 确保先获取所有权限
    if (allPermissions.value.length === 0) {
      await fetchAllPermissions();
    }

    // 然后获取角色权限并设置选中状态
    await fetchRolePermissions(role.id);

    // 设置默认选中的类别（选择第一个类别）
    const categories = Object.keys(groupedPermissions.value);
    if (categories.length > 0) {
      selectedCategory.value = categories[0];
    }

  } catch (error) {
    console.error("打开分配权限对话框失败:", error);
    ElMessage.error("打开分配权限对话框失败");
  } finally {
    assignPermissionsLoading.value = false;
  }
}

// 选择当前类别下的所有权限
function selectAllInCategory() {
  if (selectedCategory.value && groupedPermissions.value[selectedCategory.value]) {
    const categoryPermissions = groupedPermissions.value[selectedCategory.value].map(p => p.id);
    // 合并当前选中的权限和类别下的权限，去重
    const allSelected = [...new Set([...selectedPermissions.value, ...categoryPermissions])];
    selectedPermissions.value = allSelected;
  }
}

// 清空当前类别下的所有权限
function clearAllInCategory() {
  if (selectedCategory.value && groupedPermissions.value[selectedCategory.value]) {
    const categoryPermissions = groupedPermissions.value[selectedCategory.value].map(p => p.id);
    // 从已选中的权限中移除当前类别的权限
    selectedPermissions.value = selectedPermissions.value.filter(id => !categoryPermissions.includes(id));
  }
}

// 按权限代码分组的计算属性
const groupedPermissions = computed(() => {
  const groups = {};
  
  allPermissions.value.forEach(permission => {
    const code = permission.permissionCode || permission.code || 'unknown';
    const groupKey = code.split('.')[0]; // 取code的第一部分作为分组键
    
    if (!groups[groupKey]) {
      groups[groupKey] = [];
    }
    groups[groupKey].push(permission);
  });
  
  // 对每个分组内的权限按code排序
  Object.keys(groups).forEach(groupKey => {
    groups[groupKey].sort((a, b) => {
      const codeA = a.permissionCode || a.code || '';
      const codeB = b.permissionCode || b.code || '';
      return codeA.localeCompare(codeB);
    });
  });
  
  // 按分组键排序，确保显示顺序一致
  const sortedGroups = {};
  Object.keys(groups).sort().forEach(key => {
    sortedGroups[key] = groups[key];
  });
  
  return sortedGroups;
});

// 获取分组显示名称
function getGroupDisplayName(groupKey) {
  const groupNames = {
    'user': '用户管理',
    'file': '文件管理',
    'role': '角色管理',
    'permission': '权限管理',
    'system': '系统管理',
    'log': '日志管理',
    'menu': '菜单管理',
    'unknown': '其他权限'
  };
  
  return groupNames[groupKey] || `${groupKey}管理`;
}

// 选择权限类别
function selectCategory(category) {
  selectedCategory.value = category;
}



// 分配权限
async function handleAssignPermissions() {
  if (!currentRole.value) return;

  assignPermissionsLoading.value = true;
  try {
    await assignPermissionToRole(currentRole.value.id, selectedPermissions.value);
    ElMessage.success("权限分配成功");
    assignPermissionsDialogVisible.value = false;
  } catch (error) {
    handleApiError(error, { showMessage: true });
  } finally {
    assignPermissionsLoading.value = false;
  }
}

//分页功能
let handleCurrentChange = async (page) => {
  currentPage.value.page = page;
  // 分页切换时不显示加载动画
  await fetchRoles(false);
};

let handleSizeChange = async (size) => {
  currentPage.value.pageSize = size;
  currentPage.value.page = 1;
  // 分页切换时不显示加载动画
  await fetchRoles(false);
};

async function handleFilter() {
  currentPage.value.page = 1; // 重置当前页为1
  await fetchRoles();
}

async function resetFilter() {
  filterForm.value = {
    roleName: '',
    status: '',
  };
  currentPage.value.page = 1;
  await fetchRoles();
}

async function handleDeleteRole() {
  deleteLoading.value = true;
  try {
    await deleteRole(deletingRowId.value);
    ElMessage.success("角色删除成功");
    deletingRowId.value = null;
    editingRowId.value = null;
    fetchRoles();
  } catch (error) {
    handleApiError(error, { showMessage: true });
  } finally {
    deleteLoading.value = false;
    deleteDialogVisible.value = false;
    isDialogOpen.value = false;
  }
}
</script>

<style scoped>
.role-management {
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 18px;
  flex-shrink: 0;
}

.el-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: visible;
  min-height: 0;
  margin-bottom: 0;
}

.el-card__body {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 24px;
  box-sizing: border-box;
  overflow: visible;
  min-height: 0;
}

/* 确保表格可以滚动 */
.el-table__body-wrapper {
  overflow-y: auto !important;
}

.el-table__body {
  overflow: visible !important;
}

/* 数据区域样式 */
.data-area {
  flex: 1;
  overflow: visible;
  padding-right: 10px;
  padding-bottom: 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.data-area .el-table {
  width: 100%;
  height: auto;
  overflow: visible;
  margin-bottom: 0;
  border: none;
}

.data-area .el-table__inner-wrapper {
  border: none;
}

/* 确保表格内容可以正常滚动 */
.data-area .el-table__body-wrapper {
  overflow-y: auto;
  max-height: 500px;
}

.data-area .el-table__body {
  overflow: visible;
}

/* 确保表头固定 */
.data-area .el-table__header-wrapper {
  position: sticky;
  top: 0;
  z-index: 2;
  background: var(--card-bg) !important;
}

/* 表头居中 */
.data-area .el-table .el-table__header-wrapper .el-table__cell {
  text-align: center !important;
  background: var(--card-bg) !important;
  font-weight: 600;
  color: var(--text-color);
}

/* 表格内容居中 */
.data-area .el-table .el-table__body-wrapper .el-table__cell {
  vertical-align: middle !important;
}

/* 确保表格内容文字居中 */
.data-area .el-table .el-table__body-wrapper .el-table__cell .cell {
  display: flex;
  text-align: center !important;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 操作按钮样式优化 */
.data-area .el-table .el-button {
  margin: 0 2px;
  padding: 4px 8px;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.data-area .el-table .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-area .el-table .el-button .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

/* 确保表格行有足够的高度 */
:deep(.el-table__row) {
  height: auto !important;
  min-height: 55px;
}

:deep(.el-table__cell) {
  padding: 10px 0 !important;
}

/* 分页区域 - 重新设计 */
.pagination-area {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  min-height: 60px;
  width: 100%;
  position: relative;
  z-index: 10;
  margin-top: 8px;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: flex-start;
  margin: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.filter-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  padding-right: 8px;
}

.filter-form .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-select .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-select .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-select .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-button {
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-form .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.filter-form .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.filter-form .el-button--default {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

.filter-form .el-button--default:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 新增角色对话框样式 */
.add-role-form {
  padding: 20px 0;
}

.add-role-form .el-form-item {
  margin-bottom: 20px;
}

.add-role-form .el-input {
  width: 100%;
}

.add-role-form .el-form-item__label {
  font-weight: 500;
  color: var(--text-color);
}

/* 新增角色对话框输入框样式 */
.add-role-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.add-role-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.add-role-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.add-role-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 筛选区域输入框样式 */
.filter-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.filter-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.filter-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.filter-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 筛选区域下拉框样式 */
.filter-form :deep(.el-select .el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.filter-form :deep(.el-select .el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.filter-form :deep(.el-select .el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

/* 确保对话框在暗色主题下也有正确的背景 */
:deep(.el-dialog) {
  background: #fff !important;
}

:deep(.el-dialog .el-dialog__header) {
  background: #fff !important;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog .el-dialog__body) {
  background: #fff !important;
}

:deep(.el-dialog .el-dialog__footer) {
  background: #fff !important;
  border-top: none;
}

/* 删除确认对话框样式 */
.delete-confirm {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  text-align: center;
}

.delete-icon {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}

.delete-message h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.delete-message p {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

/* 分配权限对话框样式 */
.assign-permissions-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.role-info {
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  color: white;
  flex-shrink: 0;
}

.role-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.role-info p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.permissions-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.section-header {
  background: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  padding: 12px 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.section-header h5 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.selected-count {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.section-header .el-button {
  border-radius: 6px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3) !important;
}

.section-header .el-button--primary:hover {
  background: linear-gradient(135deg, #1890ff 0%, #0969da 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4) !important;
}

.section-header .el-button--info {
  background: #ffffff !important;
  border: 1px solid #d4d7de !important;
  color: #606266 !important;
}

.section-header .el-button--info:hover {
  background: #f5f7fa !important;
  border-color: #c0c4cc !important;
  color: #303133 !important;
}

.permissions-list {
  padding: 16px;
  background: #ffffff;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
}

/* 权限容器布局 */
.permissions-container {
  display: flex;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

/* 左侧类别列表 */
.category-list {
  width: 150px;
  background: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.category-item {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.category-item:hover {
  background: #e4e7ed;
}

.category-item.active {
  background: #409eff;
  color: white;
}

.category-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #1890ff;
}

.category-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-name {
  font-size: 14px;
  font-weight: 500;
}

.category-count {
  background: rgba(255, 255, 255, 0.2);
  color: inherit;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

/* 右侧权限内容 */
.permissions-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.category-permissions {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.category-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafbfc;
}

.category-header h5 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.category-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-actions {
  display: flex;
  gap: 8px;
}

.no-category-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.permission-item {
  margin-bottom: 12px !important;
  padding: 16px !important;
  border: 1px solid #e4e7ed !important;
  border-radius: 8px !important;
  background: #ffffff !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  position: relative !important;
  height: 80px !important;
  min-height: 80px !important;
  max-height: 80px !important;
  display: flex !important;
  align-items: center !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
}

.permission-item:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%) !important;
  border-color: #409eff !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15) !important;
}

.permission-item:last-child {
  margin-bottom: 0 !important;
}

.permission-item .el-checkbox {
  width: 100% !important;
  margin-right: 0 !important;
  display: flex !important;
  align-items: center !important;
  position: relative !important;
  z-index: 1 !important;
  height: 100% !important;
}

.permission-item .el-checkbox__input {
  margin-top: 0 !important;
  flex-shrink: 0 !important;
}

.permission-item .el-checkbox__label {
  width: 100% !important;
  padding-left: 16px !important;
  line-height: 1.5 !important;
  height: 100% !important;
  display: flex !important;
  align-items: center !important;
}

.permission-info {
  display: flex !important;
  flex-direction: column !important;
  gap: 6px !important;
  flex: 1 !important;
  height: 100% !important;
  justify-content: center !important;
  overflow: hidden !important;
  max-height: 100% !important;
}

.permission-name {
  font-weight: 600 !important;
  color: #303133 !important;
  font-size: 14px !important;
  line-height: 1.2 !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  flex-shrink: 0 !important;
}

.permission-desc {
  font-size: 12px !important;
  color: #909399 !important;
  line-height: 1.3 !important;
  font-weight: 400 !important;
  display: -webkit-box !important;
  -webkit-line-clamp: 2 !important;
  -webkit-box-orient: vertical !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  max-height: 32px !important;
  flex: 1 !important;
  word-break: break-all !important;
}

/* 分页禁用样式 */
.pagination-disabled {
  pointer-events: none !important;
  opacity: 0.5 !important;
}

.pagination-disabled .el-pagination {
  pointer-events: none !important;
}

.pagination-disabled .el-pagination .el-pagination__sizes,
.pagination-disabled .el-pagination .el-pagination__total,
.pagination-disabled .el-pagination .el-pager,
.pagination-disabled .el-pagination .el-pagination__jump {
  pointer-events: none !important;
  opacity: 0.5 !important;
}

/* 对话框整体样式优化 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: #fff !important;
}

:deep(.el-dialog__header) {
  background: #fff !important;
  color: #303133;
  padding: 20px 24px;
  margin: 0;
  position: relative;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__header::before) {
  display: none;
}

:deep(.el-dialog__title) {
  color: #303133;
  font-weight: 600;
  font-size: 18px;
  letter-spacing: 0.5px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #909399;
  font-size: 18px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  transform: scale(1.1) rotate(90deg);
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

:deep(.el-dialog__body) {
  padding: 24px;
  background: #fff !important;
}

:deep(.el-dialog__footer) {
  background: #fff !important;
  border-top: none;
  padding: 16px 24px;
  box-shadow: none;
}

/* 按钮样式优化 */
.dialog-footer .el-button {
  border-radius: 8px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 14px;
  letter-spacing: 0.3px;
}

.dialog-footer .el-button--default {
  background: #ffffff;
  border: 2px solid #dcdfe6;
  color: #606266;
}

.dialog-footer .el-button--default:hover {
  background: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%) !important;
  border: none !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
}

.dialog-footer .el-button--primary:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4) !important;
  background: linear-gradient(135deg, #1890ff 0%, #0969da 100%) !important;
}

/* 确保对话框遮罩层正确覆盖分页区域 */
.el-dialog__wrapper {
  z-index: 3000 !important;
}

.el-overlay {
  z-index: 2999 !important;
}

/* 确保分页区域在对话框打开时被正确遮挡 */
.el-dialog__wrapper + .el-overlay {
  z-index: 2998 !important;
}

/* 确保对话框本身在最上层 */
.el-dialog {
  z-index: 3001 !important;
}

/* 加载状态优化 */
.assign-permissions-content.loading {
  opacity: 0.7;
  pointer-events: none;
}

.assign-permissions-content.loading::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40px;
  height: 40px;
  margin: -20px 0 0 -20px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  z-index: 1000;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 复选框样式优化 */
.permission-item .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
}

.permission-item .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #409eff;
  font-weight: 600;
}

.permission-item .el-checkbox__inner:hover {
  border-color: #409eff;
}

.permission-item .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: #409eff;
}

/* 表格样式优化 */
.data-area .el-table {
  border: none;
}

.data-area .el-table th.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table td.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table--border {
  border: none;
}

.data-area .el-table--border::after {
  display: none;
}

.data-area .el-table--border .el-table__inner-wrapper::after {
  display: none;
}

.data-area .el-table--border .el-table__border-left-patch {
  display: none;
}

/* 表格内输入框居中样式 */
.center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 确保编辑状态下的输入框内容居中 */
.data-area .el-table .center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 表格内编辑输入框样式 - 只有下边框线 */
.data-area .el-table .center-input :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.data-area .el-table .center-input :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.data-area .el-table .center-input :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.data-area .el-table .center-input :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 10px;
    margin-left: 0;
    margin-top: 0;
  }
  
  .filter-form {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .filter-form .el-form-item {
    margin-bottom: 10px;
  }
  
  .filter-form .el-input,
  .filter-form .el-select {
    width: 100% !important;
  }
  
  .data-area {
    padding-right: 5px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-table th.el-table__cell,
  .el-table td.el-table__cell {
    padding: 8px 4px;
  }
}

@media (max-width: 480px) {
  .role-management {
    padding: 5px;
    margin-left: 0;
    margin-top: 0;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .el-table {
    font-size: 11px;
  }
  
  .el-table th.el-table__cell,
  .el-table td.el-table__cell {
    padding: 6px 2px;
  }
}
</style>
